/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/

#include "kperformance.h"
#include <fstream>
#include <map>

#ifdef WIN32
#include <Windows.h>

uint64_t kPerformance::getTime() {
	LARGE_INTEGER result;
	QueryPerformanceCounter(&result);
	return result.QuadPart;
}
#else
#include <time.h>

uint64_t kPerformance::getTime() {
	timespec t;
	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t);
	return t.tv_sec*1000000000ull + t.tv_nsec;
}
#endif

std::unordered_map<const tchar*, uint64_t> kPerformance::_timings;
uint64_t kPerformance::_baseTime = 0;

void kPerformance::save(const std::tstring& filename) {
	uint64_t maxTime = 0;
	uint64_t totalTime = getTime() - _baseTime;
	
	std::tofstream fs(filename, std::ios_base::out | std::ios_base::trunc);
	std::multimap<uint64_t, const tchar*> perfs;

	for (auto i = _timings.begin(); i != _timings.end(); i++) {
		perfs.insert(std::make_pair(i->second, i->first));
		maxTime = (std::max)(maxTime, i->second);
	}
	for (auto i = perfs.rbegin(); i != perfs.rend(); i++) {
		unsigned ratio = (unsigned)((1000*i->first)/totalTime);
		unsigned ratio2 = (unsigned)((100*i->first)/maxTime);
		fs << i->second << _T(" - ") << ratio*0.1 << _T("%") << std::endl;

		for (unsigned j = 0; j <= ratio2; j++)
			fs << _T("=");

		fs << std::endl << std::endl;
	}
}
